package cc.facesign.admin.dao.xls.impl;

import cc.facesign.admin.bean.TblConfUser;
import cc.facesign.admin.bean.TblUser;
import cc.facesign.admin.bean.query.UserQuery;
import cc.facesign.admin.bean.vo.UserVo;
import cc.facesign.admin.bean.xls.AddConfUserXls;
import cc.facesign.admin.bean.xls.AddDeptUserXls;
import cc.facesign.admin.client.OssClient;
import cc.facesign.admin.dao.xls.XlsDao;
import cc.facesign.admin.enums.GenderType;
import cc.facesign.admin.service.*;
import cc.facesign.admin.utils.IOUtils;
import cc.facesign.admin.utils.PowerUtils;
import cc.facesign.admin.utils.RedisKey;
import cc.facesign.servicebase.utils.RedisCache;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Repository
@Slf4j
public class XlsDaoImpl implements XlsDao {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private TblUserService userService;

    @Autowired
    private OssClient ossClient;

    @Autowired
    private PowerUtils powerUtils;

    @Autowired
    private TblConfUserService confUserService;

    @Autowired
    private AclService aclService;

    @Autowired
    private TblDeptService deptService;

    @Override
    public List<AddDeptUserXls> saveForAddUserInDept(List<AddDeptUserXls> date, List<MultipartFile> pics, String deptId){
        Map<String, MultipartFile> map = IOUtils.getFiles(pics);

        // 存该单位的所有用户cardId，防止cardId冲突
        UserQuery query = new UserQuery();
        query.setRootDeptId(deptService.getRid(deptId));
        HashSet<String> set = userService.getInfoListByQuery(query).stream()
                .map(x -> x.getCardId())
                .collect(Collectors.toCollection(HashSet::new));


        List<TblUser> success = new ArrayList<>();
        List<AddDeptUserXls> errs = new ArrayList<>();

        for (AddDeptUserXls e : date) {
            TblUser user = new TblUser();
            BeanUtils.copyProperties(e, user);

            String cardId = e.getCardId();
            if (set.contains(cardId)) {
                log.info("xls id冲突 - {}", e);
                errs.add(e);
                continue;
            }

            String secret = aclService.getSecret(e.getPassword());
            user.setPassword(secret);

            // 头像 上传用户头像：身份证.jpg
            MultipartFile multipartFile = map.get(cardId+".jpg");
            if (multipartFile == null) {
                log.info("xls 头像问题 - {}", e);
                errs.add(e);
                continue;
            }
            String avatar = ossClient.upload(multipartFile).getData().get("url").toString();
            user.setAvatar(avatar);

            // 性别
            Integer gender = GenderType.deCodeOf(e.getGender());
            if (gender == null) {
                log.info("xls 性别空 - {}", e);
                errs.add(e);
                continue;
            }

            user.setGender(gender);
            user.setDeptId(deptId);
            success.add(user);
        }

        // 批量保存
        userService.saveBatch(success);

        if (success.size() != 0) redisCache.setCacheList(RedisKey.XLS_UPLOAD_DEPT_USER_SUCCESS+powerUtils.getId(), success);

        return errs;
    }

    @Autowired
    private TblConfService confService;

    @Override
    public List<AddConfUserXls> saveForAddUserInConf(List<AddConfUserXls> data, String confId) {
        String rid = deptService.getRid(confService.getById(confId).getDeptId());

        UserQuery query = new UserQuery();
        query.setRootDeptId(rid);
        // key:cardId value:vo
        Map<String, UserVo> map = userService.getInfoListByQuery(query).stream()
                .collect(Collectors.toMap(UserVo::getCardId, UserVo -> UserVo));

        List<TblConfUser> list = new ArrayList<>();
        List<AddConfUserXls> errs = new ArrayList<>();
      //  System.out.println("**2 "+ list);

        for (AddConfUserXls e : data) {
            String name = e.getName();
            String phone = e.getPhone();
            String cardId = e.getCardId();

            // 信息不能为空
            if (StringUtils.isEmpty(name) || StringUtils.isEmpty(phone) || StringUtils.isEmpty(cardId)) {
                errs.add(e);
                log.error("xls向会议添加用户, {} 用户存在 [空数据] 异常", e);
                continue;
            }

            // 不存在该身份证用户
            if (!map.containsKey(cardId)) {
                errs.add(e);
                log.error("xls向会议添加用户, {} 用户存在 [不存在该身份证] 异常", e);
                continue;
            }

            UserVo vo = map.get(cardId);
            TblConfUser confUser = new TblConfUser();
            confUser.setConfId(confId);
            confUser.setUserId(vo.getId());


            // 对用户输入的信息进行校验匹配，防止恶搞
            if (!vo.getName().equals(e.getName())) {
                errs.add(e);
                log.error("xls向会议添加用户, {} 用户存在 [名字信息不一致] 异常", e);
                continue;
            }

            list.add(confUser);

        }


        confUserService.relateBatch(list);

        if (list.size() != 0) redisCache.setCacheList(RedisKey.XLS_UPLOAD_CONF_USER_SUCCESS+powerUtils.getId(), list);

        return errs;
    }

}
